package com.zh.seckill.controller;


import com.zh.seckill.pojo.User;
import com.zh.seckill.service.GoodsService;
import com.zh.seckill.service.UserService;
import com.zh.seckill.vo.GoodsVo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Resource
    private UserService userService;

    @Resource
    private GoodsService goodsService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ThymeleafViewResolver thymeleafViewResolver;


//------------------------引入WebMvcConfigurer拦截处理User----------------------------------
    //    @RequestMapping("/toList")
//    public String toList(Model model, @CookieValue("userTicket") String ticket,
//                         HttpServletRequest request, HttpServletResponse response) {
//        if (!StringUtils.hasText(ticket)) {
//            return "login";
//        }
////      User user =(User) session.getAttribute(ticket);
//        User user = userService.getUserByCookie(ticket, request, response);
//        if (user == null) {
//            return "login";
//        }
//        model.addAttribute("user", user);
//        return "goodsList";
//    }

    //--------------------------原生到db查询---------------------------------

//    @RequestMapping("/toList")
//    public String toList(Model model, User user) {
//
//        if (user == null) {
//            return "login";
//        }
//        model.addAttribute("user", user);
//        // 获取商品列表
//        model.addAttribute("goodsList", goodsService.findGoodsVo());
//        return "goodsList";
//    }


    //-------------------------------//到redis查询//---------------------------
    @RequestMapping(value = "/toList", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toList(Model model, User user, HttpServletResponse response, HttpServletRequest request) {

        if (user == null) {
            return "login";
        }

        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsList");
        if (StringUtils.hasText(html)) {
            return html;
        }

        model.addAttribute("user", user);
        // 获取商品列表
        model.addAttribute("goodsList", goodsService.findGoodsVo());

        //如果redis没有获取页面，手动渲染，存入到redis
        WebContext webContext = new WebContext(request, response,
                request.getServletContext(), request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsList", webContext);
        if (StringUtils.hasText(html)) {
            //保存到redis，每60秒刷新一次
            valueOperations.set("goodsList", html, 60, TimeUnit.SECONDS);
        }


        return html;
    }


    @RequestMapping(value = "/toDetail/{goodsId}", produces = "text/html;charset=utf-8")
    @ResponseBody
    public String goodsDetail(Model model, User user, @PathVariable Long goodsId,
    HttpServletRequest request, HttpServletResponse response) {

        if (user == null) {
            return "login";
        }

        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsDetail:"+goodsId);
        if (StringUtils.hasText(html)) {
            return html;
        }

        model.addAttribute("user", user);
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        model.addAttribute("goods", goodsVo);
        //1. 变量 secKillStatus 秒杀状态 0:秒杀未开始 1: 秒杀进行中 2: 秒杀已经结束
        //2. 变量 remainSeconds 剩余秒数: >0: 表示还有多久开始秒杀: 0: 秒杀进行中 -1: 表示秒杀已经结束

        //秒杀开始时间
        Date startDate = goodsVo.getStartDate();
        //秒杀结束时间
        Date endDate = goodsVo.getEndDate();
        //当前时间
        Date nowDate = new Date();

        //秒杀状态
        int secKillStatus = 0;
        //秒杀剩余时间-秒
        int remainSeconds = 0;

        //如果nowDate 在 startDate 前, 还没有开始秒杀
        if (nowDate.before(startDate)) {
            //得到还有多少秒开始秒杀
            remainSeconds = (int) ((startDate.getTime() - nowDate.getTime()) / 1000);
        } else if (nowDate.after(endDate)) {//说明秒杀已经结束
            secKillStatus = 2;
            remainSeconds = -1;
        } else { //秒杀进行中
            secKillStatus = 1;
            remainSeconds = 0;
        }

        model.addAttribute("secKillStatus", secKillStatus);
        model.addAttribute("remainSeconds", remainSeconds);



        //如果redis没有获取页面，手动渲染，存入到redis
        WebContext webContext = new WebContext(request, response,
                request.getServletContext(), request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", webContext);
        if (StringUtils.hasText(html)) {
            //保存到redis，每60秒刷新一次
            valueOperations.set("goodsDetail:" + goodsId, html, 60, TimeUnit.SECONDS);
        }
        return html;
    }
}
